package cafe.ejb;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import cafe.ejb.myexceptions.EntityNotFoundException;
import cafe.jpa.Order;
import cafe.jpa.Waiter;

/**
 * Session Bean implementation class OrderServiceBean
 */
@Stateless
@Local(OrderService.class)
public class OrderServiceBean implements OrderService {	
	
	@PersistenceContext(unitName="cafe.jpa")
	private EntityManager em;

    /**
     * Default constructor. 
     */
    public OrderServiceBean() { }

	@Override
	public Order getOrderByID(long id) throws EntityNotFoundException,SQLException {
		Query q = em.createQuery("select ow from Order o where o.id = :id");
		q.setParameter("id", id);
        return (Order) q.getSingleResult();
		
	}

	@Override
	public List<Order> getAllOrders() throws SQLException,
			EntityNotFoundException {
		
		Query q = em.createQuery("select o from Order o");        
        return (List<Order>) q.getResultList();       
	}

	@Override
	public void addOrder(Order order) throws SQLException {
		em.persist(order);		
	}

	@Override
	public void update(Order order) {		
		
	}

	@Override
	public void removeByID(long id) throws SQLException {
		Query q = em.createQuery("DELETE FROM Order o	WHERE o.id = :id");
		q.setParameter("id", id);
        q.executeUpdate();
	}

	@Override
	public Set<Waiter> getOrdersWaiters(long orderId) throws EntityNotFoundException, SQLException {		
		Order order = getOrderByID(orderId);
		return order.getWaiters();
	}

	

}
